import 'package:flame/components.dart';
import 'package:flutter/material.dart';

class DamageText extends PositionComponent {
  final TextStyle _textStyle = TextStyle(
      fontSize: 14,
      color: Colors.white,
      fontFamily: 'Menlo',
      shadows: [
        Shadow(color: Colors.red, offset: Offset(1, 1), blurRadius: 1)
      ]);

  final TextStyle _critTextStyle = TextStyle(
      fontSize: 14,
      color: Colors.yellowAccent,
      fontFamily: 'Menlo',
      shadows: [
        Shadow(color: Colors.red, offset: Offset(1, 1), blurRadius: 1)
      ]);

  void addImage(int damage, {bool isCrit = false}) {
    Vector2 offSet = Vector2(-30, 0);
    if (children.isNotEmpty) {
      final PositionComponent last;
      if (children.last is PositionComponent) {
        last = children.last as PositionComponent;
        offSet = last.position + Vector2(5, last.height);
      }
    }
    if (!isCrit) {
      _addWhiteImage(damage, offSet);
    } else {
      _addCritDamage(damage, offSet);
    }
  }

  Future<void> _addWhiteImage(int damage, Vector2 offSet) async {
    TextComponent damageText =
        TextComponent(textRenderer: TextPaint(style: _textStyle));
    damageText.text = damage.toString();
    damageText.position = offSet;
    add(damageText);
    await Future.delayed(const Duration(seconds: 1));
    damageText.removeFromParent();
  }

  _addCritDamage(int damage, Vector2 offSet) async {
    TextComponent damageText =
        TextComponent(textRenderer: TextPaint(style: _critTextStyle));
    damageText.text = damage.toString();
    damageText.position = Vector2(-30, 0);
    TextStyle style = _critTextStyle.copyWith(fontSize: 10);
    TextComponent infoText =
        TextComponent(textRenderer: TextPaint(style: style));
    infoText.text = '暴击';
    infoText.position = Vector2(
        -30 + damageText.width - infoText.width / 2, -infoText.height / 2);
    add(infoText);
    add(damageText);
    await Future.delayed(const Duration(seconds: 1));
    infoText.removeFromParent();
    damageText.removeFromParent();
  }
}
